package qe.spider.grab;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.UnicodeUtil;
import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import qe.spider.vo.StockList;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//同花顺问财-最近5个交易日有过涨停或跌停
@Slf4j
public class GrabWenCai {
    private String token;

    public GrabWenCai(String token) {
        this.token = token;
    }

    public static void main(String[] args) throws IOException {
        String token = "A1_yNvt-RkXRg0JwHZvMQNOi7rjsxLtBzRO3UvGs-LZVnnGm-ZRDtt3oR_wC";
        new GrabWenCai(token).grab("000919,002693,601998,000705,603949最近5个交易日有过涨停或跌停吗");
    }


    public String buildJson(String question) {
        Map<String, Object> msg = new HashMap<>();
        msg.put("source", "Ths_iwencai_Xuangu");
        msg.put("version", "2.0");
        msg.put("query_area", "");
        msg.put("block_list", "");
        msg.put("add_info", "{\"urp\":{\"scene\":1,\"company\":1,\"business\":1},\"contentType\":\"json\",\"searchInfo\":true}");
        msg.put("question", question);
        msg.put("perpage", 100);
        msg.put("page", "1");
        msg.put("secondary_intent", "stock");
        msg.put("log_info", "{\"input_type\":\"typewrite\"}");
        msg.put("rsh", "Ths_iwencai_Xuangu_f5b8nris42og20e5hbyxvxruq45c7z7n");
        String json = new Gson().toJson(msg);
        return json;
    }

    public String grab(String question) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), buildJson(question));

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("https://www.iwencai.com/customized/chart/get-robot-data")
//                .header("Accept-Encoding", "gzip, deflate, br")
                .header("Accept", "application/json, text/plain, */*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Connection", "keep-alive")
                .header("Cache-Control", "no-cache")
                .header("Content-Type", "application/json")
                .header("Host", "www.iwencai.com")
                .header("Origin", "https://www.iwencai.com")
                .header("Pragma", "no-cache")
                .header("hexin-v", token)
                .header("sec-ch-ua", "\"Not_A Brand\";v=\"99\", \"Microsoft Edge\";v=\"109\", \"Chromium\";v=\"109\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-site")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.140")
                .post(body)
                .build();
        Gson gson = new Gson();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);


            String result = UnicodeUtil.toString(response.body().string());
            log.info(result);
            if (result.contains("forbidden"))
                throw new IOException("问财访问令牌过期或被封了，请更新token后再试！" + result);
            return result;
        }

    }

    public JsonArray parseAnswer(String json) {
        try {
            JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
            jsonObject.getAsJsonObject();
            JsonArray answer = jsonObject.getAsJsonObject("data").getAsJsonArray("answer").get(0).getAsJsonObject().getAsJsonArray("txt").get(0).getAsJsonObject().getAsJsonObject("content").getAsJsonArray("components");
            return answer;
        } catch (Exception e) {
            log.error("问财数据解析错误", e);
            throw new RuntimeException("问财数据解析错误");
        }
    }


}
